package ricky.scene
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.system.ApplicationDomain;
	
	import ricky.Interface.IDispose;
	import ricky.events.CameraEvent;
	import ricky.loader.LoadingView;
	import ricky.loader.MultipleLoader;
	import ricky.loader.Request;
	import ricky.quadtree.Quadtree;

	/**
	 * 场景管理类
	 */
	public class Scene extends Sprite implements IDispose
	{
		public function Scene(enableStage3D:Boolean=true)
		{
			_multipleLoader=MultipleLoader.instance;
			_tree=new Quadtree();
			_characterLayout=new Sprite();
			var stage3DAvailable:Boolean = 	ApplicationDomain.currentDomain.hasDefinition("flash.display.Stage3D");
//			if (stage3DAvailable && enableStage3D)
//				_mapLayout=new Stage3DMapLayout();
//			else
				_mapLayout=new MapLayout();
			
			_mapLayout.tilePathFun=getTilePath;
			
			if(!stage)
				this.addEventListener(Event.ADDED_TO_STAGE,init);
			else
				init(null);

		}

		/** 是否初始化 */
		public function initialized():Boolean
		{
			return _initialized;
		}

		/**
		 * 加载地图
		 * @param mapURL:String 地图路径
		 * @param onComplete():Function 数据和小地图加完后调用事件
		 * @param onProgress:Function loading事件
		 */
		public function loadMap(mapURL:String,onComplete:Function,onProgress:Function=null):void
		{
			_allLoadComplete=onComplete;
			var req:Request=new Request(mapURL,onMapDataComplete,2);
			_multipleLoader.loadReq([req],null,onProgress);
		}
		
		/**
		 * 加载地图
		 * @param mapData:MapData 地图数据
		 * @param onComplete():Function 数据和小地图加完后调用事件
		 * @param onProgress:Function loading事件
		 */
		public function loadMapByFile(mapData:MapData,onComplete:Function,onProgress:Function=null):void
		{
			_allLoadComplete=onComplete;
			var e:Request=new Request(mapData.mapURLPath+mapData.name);
			e.data=mapData;
			onMapDataComplete(e);
		}
		
		/**
		 * 清除场景所以对象
		 */
		public function clear():void
		{
			var obj:Object;
			while(_characterLayout.numChildren>0)
			{
				obj=_characterLayout.removeChildAt(0);
				if(obj is IDispose)
					IDispose(obj).dispose();
			}
			
			this._mapLayout.clear();
			
		}
		
		//**************** 接口实现 IDispose ****************
		
		public function dispose():void
		{
			_mapData=null;
			_mapLayout.dispose();
			_mapLayout=null;	
			_multipleLoader=null;
		}
		
		////////////////////////////////////////////////////////
		//****************  ****************
		///////////////////////////////////////////////////////////
		
		/**
		 * 初始化场景
		 */
		protected function init(e:Event):void
		{
			if(!camera)
				camera=new Camera(0,0,stage.stageWidth,stage.stageHeight);

			this.addChild(_mapLayout);
			this.addChild(_characterLayout);
			
			_initialized=true;
		}
		
		/**
		 * 得到i,j格子资源路径
		 */
		protected function getTilePath(i:int,j:int):String
		{
			return _mapData.mapURLPath+"\\"+(int(j*this.gridMaxSize)+i+1)+".jpg";
		}
		
		/**
		 * 镜头移动事件 
		 */
		protected function onCameraMoving(e:CameraEvent):void
		{
			if(!_initialized)
				return;
			
			if(e.camera)
				scrollRect=e.camera;
			this._mapLayout.moveing();
		}
		
		/**
		 * 镜头大小改变，远近
		 */
		protected function onCameraResize(e:CameraEvent):void
		{
			if(!_initialized)
				return;
			
			onCameraGridChange(e);
			scrollRect=e.camera;
//			this._mapLayout.
		}
		
		/**
		 * 地图格子坐标改变
		 */
		protected function onCameraGridChange(e:CameraEvent):void
		{
			if(!_initialized)
				return;
			
			var gx:int=e.camera.gridX;
			var gy:int=e.camera.gridY;
			var gwidth:int=e.camera.gridBufferWidth;
			var gheight:int=e.camera.gridBufferHeight;
			this._mapLayout.loadResource(gx,gy,gwidth,gheight);
		}
		
		/**
		 * 地图数据加载完成，开始加载小地图
		 */
		protected function onMapDataComplete(e:Request):void
		{
			this.clear();

			_mapData=e.data;
			initData();

			var req:Request=new Request(_mapData.smallMapURL,onSmallMapLoaded);
			req.onEnd=onSmallMapLoaded;
			_multipleLoader.addReqToQueue(req);
		}
		
		protected function initData():void
		{
			gridMaxSize=Math.ceil(_mapData.width/_mapData.gridWidth);//取最大值
			
			initCamera();
			
			this._mapLayout.setGridInfo(_mapData.gridWidth,_mapData.gridHeight);
			
			_tree=new Quadtree();
			var maxCol:int=mapData.col; //Math.floor(mapData.width/mapData.titleWidth);//取最小值
			_tree.buildTreeBySingleArray(mapData.data,maxCol);
			this._characterLayout.graphics.beginFill(0,0);
			this._characterLayout.graphics.drawRect(0,0,_mapData.width,_mapData.height);
			this._characterLayout.graphics.endFill();
			
		}
		
		/**
		 * 初始化镜头相关数据
		 */
		protected function initCamera():void
		{
			if(camera)
			{
				camera.maxWidth=_mapData.width;
				camera.maxHeight=_mapData.height;
				camera.gridWidth=_mapData.gridWidth;
				camera.gridHeight=_mapData.gridHeight;
			}
		}
		
		protected function onSmallMapLoaded(r:Request):void
		{
			if(r.data)
			{
				_smallBmp=r.data.bitmapData;
				if(!(_mapLayout instanceof Stage3DMapLayout))
				{
					var g:Graphics=this.graphics;
					var matrix:Matrix=new Matrix();
					matrix.scale(_mapData.width/_smallBmp.width,_mapData.height/_smallBmp.height);
					g.beginBitmapFill(_smallBmp,matrix,true,true);
					g.drawRect(0,0,_mapData.width,_mapData.height);
					g.endFill();
				}
			}
			if(_allLoadComplete!=null)
				_allLoadComplete.apply();
			
			_allLoadComplete=null;
		}
		
		private var _allLoadComplete:Function;
		
		//**************** 属性 ****************

		/**
		 * 角色层
		 */
		public function get characterLayout():Sprite
		{
			return _characterLayout;
		}
		
		public function get multipleLoader():MultipleLoader
		{
			return _multipleLoader;
		}
		
		/**
		 * ditu shuju
		 */
		public function get mapData():MapData
		{
			return _mapData;
		}
		
		/** 存储游戏对像的索引 四叉树 */
		public function get tree():Quadtree
		{
			return _tree;
		}
		
		/**
		 * 格子定位x起点座标
		 */
		public function get getVertexGridX():int
		{
			if(this._initialized)
				return this._camera.x/_mapData.gridWidth;
			return 0;
		}
		
		/**
		 * 格子定位y起点座标
		 */
		public function get getVertexGridY():int
		{
			if(this._initialized)
				return this._camera.y/_mapData.gridHeight;
			return 0;
		}
		
		/**
		 * 镜头
		 */
		public function get camera():Camera
		{
			return _camera;
		}

		/**
		 * @private
		 */
		public function set camera(value:Camera):void
		{
			if(_camera)
			{
				_camera.removeEventListener(CameraEvent.Camera_Move,onCameraMoving);
				_camera.removeEventListener(CameraEvent.Camera_Resize,onCameraResize);
				_camera.removeEventListener(CameraEvent.Camera_Grid_Change,onCameraGridChange);
				_camera=null;
			}
			_camera = value;
			if(this._initialized)
			{
				initCamera();
			}
			_camera.addEventListener(CameraEvent.Camera_Move,onCameraMoving);
			_camera.addEventListener(CameraEvent.Camera_Resize,onCameraResize);
			_camera.addEventListener(CameraEvent.Camera_Grid_Change,onCameraGridChange);
			
		}

		/**
		 * 地图层
		 */
		public function get map():MapLayout
		{
			return _mapLayout;
		}

		/**
		 * 小地图
		 */
		public function get smallBmp():BitmapData
		{
			return _smallBmp;
		}

		/**
		 * @private
		 */
		public function set smallBmp(value:BitmapData):void
		{
			_smallBmp = value;
		}

		/**
		 * 格子最大个数
		 */
		public var gridMaxSize:int;

		protected var _smallBmp:BitmapData;//小地图
		
		protected var _mapLayout:MapLayout;
		
		protected var _camera:Camera;
		
		protected var _mapData:MapData;
		
		protected var _multipleLoader:MultipleLoader;
		
		protected var _characterLayout:Sprite;
		
		private var _tree:Quadtree;//游戏对象
		
		private var _initialized:Boolean=false;//
	}
}